﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Micronet.OpenWeb.Com.Controls;
using Micronet.OpenWeb.Entity;
using Micronet.OpenWeb.OpenWeb;
using Micronet.OpenWeb.Utils;
using Telerik.Web.UI;
using System.Web.Security;
using Micronet.OpenWeb.Com.BLL;
namespace Micronet.OpenWeb.Com.ControlLib
{
    public partial class ViewCart : UserControl
    {
        private MyCart _cart;
        //private int _updateCart;
        private int UpdateCart
        {
            get { return Convert.ToInt32(ViewState["updateCart"]); }
            set { ViewState["updateCart"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _cart = (MyCart)Session["MyCart"] ?? new MyCart();
            if (!IsPostBack)
            {
                FillMyCart();
                UpdateCart = 1;
                Notify.Visible = false;
                InformationCustomer.Visible = false;
                InformationLogin.Visible = false;
                CopyCustInfoToShipInfoCheckBox.Visible = false;
                CopyOldShipInfoToShippInfoCheckBox.Visible = false;
            }
            Response.Write(UserId);
            // Nếu đăng nhập thành công
            if ("logined".OwQsIsExist())
            {
                InformationLogin.Visible = true;
                InformationCustomer.Visible = true;
                Notify.Visible = false;
                CopyCustInfoToShipInfoCheckBox.Visible = true;
                CopyOldShipInfoToShippInfoCheckBox.Visible = true;
                //Load dữ liệu customer theo user ID (1 customerid -> 1 userid) nếu đã có trong customer
                LoadCustomerInfo();
            }
        }

        protected Guid? UserId
        {
            get
            {
                var membershipUser = Membership.GetUser();
                if (membershipUser != null)
                {
                    if (membershipUser.ProviderUserKey != null)
                        return new Guid(membershipUser.ProviderUserKey.ToString());
                }
                return null;
            }
        }

        private void FillMyCart()
        {
            ViewCartGrid.DataSource = _cart;
            ViewCartGrid.DataBind();

            //refresh thong tin gio hang
            //ASP.site_master master = (ASP.site_master)this.Master;
            //master.RefreshShoppingCartInfo();

            if (_cart.Count > 0)
            {
                var footer = (GridFooterItem)ViewCartGrid.MasterTableView.GetItems(GridItemType.Footer)[0];
                footer["Amount"].Text = "$ " + _cart.Total.ToString("#.#0");
            }

            var hasRow = _cart.Count > 0;
            PaymentImageButton.Enabled = hasRow;
        }

        protected void QuantityTextBox_TextChanged(object sender, EventArgs e)
        {
            //Neu sua doi set co UpdateCart=0
            UpdateCart = 0;
        }

        protected void UpdateImageButton_Click(object sender, ImageClickEventArgs e)
        {
            foreach (GridDataItem dataItem in ViewCartGrid.Items)
            {
                var productId = dataItem.GetDataKeyValue("ShopProductID").OwToInt64TryParse();
                var tbxQuantity = (OwTextBox)dataItem["Quantity"].FindControl("QuantityTextBox");
                var quantity = tbxQuantity.Text.OwToDouble();
                _cart.Update(productId, quantity);
            }

            FillMyCart();
            UpdateCart = 1;
            ErUpdate.Visible = false;
        }

        protected void PaymentImageButton_Click(object sender, ImageClickEventArgs e)
        {
            if (UpdateCart == 0)
            {
                ErUpdate.Visible = true;
            }
            else
            {
                // Nếu đã đăng nhập
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    Login1.Visible = false;
                    Notify.Visible = false;
                    CopyCustInfoToShipInfoCheckBox.Visible = true;
                    CopyOldShipInfoToShippInfoCheckBox.Visible = true;
                    InformationLogin.Visible = true;
                    InformationCustomer.Visible = true;
                    //Load dữ liệu customer theo user ID (1 customerid -> 1 userid) nếu đã có trong customer
                    LoadCustomerInfo();
                }
                else
                {
                    //Có đăng nhập không
                    Notify.Visible = true;
                }
            }
        }

        private void LoadCustomerInfo()
        {
            if (OwCustomersBLL.OwGetByDynamic(userID: UserId).Count > 0)
            {
                var owCustomersEntity = OwCustomersBLL.OwGetByDynamic(userID: UserId)[0];
                CustomerIDTextBox.Text = owCustomersEntity.CustomerID.OwToString();
                NameCustTextBox.Text = owCustomersEntity.Name;
                AddCustTextBox.Text = owCustomersEntity.Address;
                EmailCustTextBox.Text = owCustomersEntity.Email;
                TelCustTextBox.Text = owCustomersEntity.Tel;
                FaxCustTextBox.Text = owCustomersEntity.Fax;
                MobileCustTextBox.Text = owCustomersEntity.Mobile;
                DescriptionCustTextBox.Text = owCustomersEntity.Description;
            }
        }

        protected void ViewCartGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            var dataItem = (GridDataItem)e.Item;
            var productId = dataItem.GetDataKeyValue("ShopProductID").OwToInt64TryParse();
            _cart.Remove(productId);
            FillMyCart();
        }

        protected void LoginLinkButton_Click(object sender, EventArgs e)
        {
            Login1.Visible = true;
        }

        protected void GoOnLinkButton_Click(object sender, EventArgs e)
        {
            Login1.Visible = false;
            InformationLogin.Visible = true;
            InformationCustomer.Visible = true;
            CopyCustInfoToShipInfoCheckBox.Visible = true;
            CopyOldShipInfoToShippInfoCheckBox.Visible = false;
        }

        protected void FinishPaymentButton_Click(object sender, EventArgs e)
        {
            bool delSession = false;
            // Nếu có trong customer: kiểm tra có chọn shipping sẵn có không
            if (OwCustomersBLL.OwGetByDynamic(userID: UserId).Count > 0 && UserId != null)
            {
                // Nếu có chọn shipping address: insert vao order va order detail
                if (AddressShippingInfoGridView.SelectedItems.Count > 0)
                {
                    var orderId = InsertToOrder(CustomerIDTextBox.Text.OwToInt64TryParse(),
                                                ShippingAddressIDTextBox.Text.OwToInt64TryParse());
                    InsertToOrderDetail(orderId);
                    delSession = true;
                }
                // Nếu không chọn trong shipping address: insert vào shipping address, order và order detail
                else
                {
                    var shippingAddressId = InsertToShippingAddress(CustomerIDTextBox.Text.OwToInt64TryParse());
                    var orderId = InsertToOrder(shippingAddressId, CustomerIDTextBox.Text.OwToInt64TryParse());
                    InsertToOrderDetail(orderId);
                    delSession = true;
                }
            }
            // Nếu không có trong customer: insert customer, shipping address, order, orderdetail
            else
            {
                var customerId = InsertToCustomer();
                var shippingAddressId = InsertToShippingAddress(customerId);
                var orderId = InsertToOrder(shippingAddressId, customerId);
                InsertToOrderDetail(orderId);
                delSession = true;
            }
            if (delSession)
            {
                "MyCart".OwSessionRemove();
            }
        }

        private long InsertToCustomer()
        {
            var owCustomersEntity = new OwCustomersEntity();
            owCustomersEntity.Name = NameCustTextBox.Text;
            owCustomersEntity.Email = EmailCustTextBox.Text;
            owCustomersEntity.Address = AddCustTextBox.Text;
            owCustomersEntity.Tel = TelCustTextBox.Text;
            owCustomersEntity.Fax = FaxCustTextBox.Text;
            owCustomersEntity.Mobile = MobileCustTextBox.Text;
            owCustomersEntity.Description = DescriptionCustTextBox.Text;
            owCustomersEntity.UserID = UserId;
            var customerId = OwCustomersBLL.OwSave(owCustomersEntity);
            if (customerId > 0)
            {
                NotifyLabel.Text += "Ok customer";
            }
            return customerId;
        }

        private long InsertToShippingAddress(long customerId)
        {
            var owShippingAddresssEntity = new OwShippingAddressesEntity();
            owShippingAddresssEntity.Name = NameShipTextBox.Text;
            owShippingAddresssEntity.Email = EmailShipTextBox.Text;
            owShippingAddresssEntity.Address = AddShipTextBox.Text;
            owShippingAddresssEntity.Tel = TelShipTextBox.Text;
            owShippingAddresssEntity.Fax = FaxShipTextBox.Text;
            owShippingAddresssEntity.Mobile = MobileShipTextBox.Text;
            owShippingAddresssEntity.Description = DescriptionShipTextBox.Text;
            owShippingAddresssEntity.CustomerID = customerId;
            owShippingAddresssEntity.DateTimeCreated = DateTime.Now;
            var shippingAddressId = OwShippingAddressesBLL.OwSave(owShippingAddresssEntity);
            if (shippingAddressId > 0)
            {
                NotifyLabel.Text += "Ok shipping address";
            }
            return shippingAddressId;
        }

        private void InsertToOrderDetail(long orderId)
        {
            foreach (DataRow Row in _cart.Rows)
            {
                var owOrderDetailsEntity = new OwOrderDetailsEntity();
                owOrderDetailsEntity.OrderID = orderId;
                /*SOS Dang su dung ProductID nhu ShopProductID*/
                //_owOrderDetailsEntity.ShopProductID =
                owOrderDetailsEntity.ProductID = Row["ShopProductID"].OwToInt64TryParse();
                /*SOS ProductName trong csdl phai sua: bigint -> nvarchar(50)*/
                /*SOS Không cần ProductName do đã có ProductID*/
                //owOrderDetailsEntity.ProductName = Row["ProductName"].OwToInt64TryParse();
                owOrderDetailsEntity.CurrentPrice = Row["CurrentPrice"].OwToDouble();
                owOrderDetailsEntity.Quantity = Row["Quantity"].OwToInt32TryParse();
                /*SOS CurrencyID*/
                /*SOS UnitID*/
                var orderDetailId = OwOrderDetailsBLL.OwSave(owOrderDetailsEntity);
                if (orderDetailId > 0)
                {
                    NotifyLabel.Text += "Ok order detail";
                }
            }
        }

        private long InsertToOrder(long shippingAddressId, long customerId)
        {
            // insert order
            DateTime dt = DateTime.Now;
            var owOrdersEntity = new OwOrdersEntity();
            owOrdersEntity.OrderNo = "Micronet" + "_" + dt.Millisecond + dt.Day;
            owOrdersEntity.Name = "Hóa đơn xuất";
            /*SOS ShopID*/
            //owOrdersEntity.ShopID =
            owOrdersEntity.CustomerID = customerId;
            owOrdersEntity.DateTimeCreated = dt;
            /*SOS IsConfirm & DateTimeConfirm nhap sau*/
            owOrdersEntity.TotalAmount = _cart.Total;
            owOrdersEntity.PaymentMethodID = PaymentMethodComboBox.SelectedValue.OwToInt64TryParse();
            owOrdersEntity.ShippingAddressID = shippingAddressId;
            owOrdersEntity.ShippingMethodID = ShippingMethodComboBox.SelectedValue.OwToInt64TryParse();
            var orderId = OwOrdersBLL.OwSave(owOrdersEntity);
            if (orderId > 0)
            {
                NotifyLabel.Text += "Ok order";
            }
            return orderId;
        }

        protected void SignUpLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/Views/Site/CreateUserLogin.aspx");
        }

        protected void ViewCartLoginStatus_LoggedOut(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/Views/Site/ViewCart.aspx");
        }

        protected void AddressShippingInfoGridView_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick")
            {
                if (e.Item is GridDataItem)
                {
                    var gridItem = e.Item as GridDataItem;
                    ShippingAddressIDTextBox.Text = gridItem["ShippingAddressID"].Text;
                    NameShipTextBox.Text = gridItem["Name"].Text;
                    AddShipTextBox.Text = gridItem["Address"].Text;
                    EmailShipTextBox.Text = gridItem["Email"].Text;
                    TelShipTextBox.Text = gridItem["Tel"].Text;
                    FaxShipTextBox.Text = gridItem["Fax"].Text;
                    MobileShipTextBox.Text = gridItem["Mobile"].Text;
                    DescriptionShipTextBox.Text = gridItem["Description"].Text;
                }
            }
        }

        private void ClearShippingAddressInfo()
        {
            ShippingAddressIDTextBox.Text = "";
            NameShipTextBox.Text = "";
            AddShipTextBox.Text = "";
            EmailShipTextBox.Text = "";
            TelShipTextBox.Text = "";
            FaxShipTextBox.Text = "";
            MobileShipTextBox.Text = "";
            DescriptionShipTextBox.Text = "";
        }

        protected void CopyCustInfoToShipInfoCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if(CopyCustInfoToShipInfoCheckBox.Checked.OwToBoolean())
            {
                CopyOldShipInfoToShippInfoCheckBox.Checked = false;
                AddressShippingInfoGridView.Visible = false;
                ClearShippingAddressInfo();
                NameShipTextBox.Text = NameCustTextBox.Text;
                AddShipTextBox.Text = AddCustTextBox.Text;
                EmailShipTextBox.Text = EmailCustTextBox.Text;
                TelShipTextBox.Text = TelCustTextBox.Text;
                FaxShipTextBox.Text = FaxCustTextBox.Text;
                MobileShipTextBox.Text = MobileCustTextBox.Text;
                DescriptionShipTextBox.Text = DescriptionCustTextBox.Text;
            }
        }

        protected void CopyOldShipInfoToShippInfoCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if(CopyOldShipInfoToShippInfoCheckBox.Checked.OwToBoolean())
            {
                // Load dữ liệu shipping address có sẵn
                CopyCustInfoToShipInfoCheckBox.Checked = false;
                AddressShippingInfoGridView.Visible = true;
                ClearShippingAddressInfo();
                var shippingAddresses = OwShippingAddressesBLL.OwGetByDynamic(customerID: CustomerIDTextBox.Text.OwToInt64TryParse());
                AddressShippingInfoGridView.DataSource = shippingAddresses;
                AddressShippingInfoGridView.DataBind();
            }
        }
    }
}